package threads;

import java.util.concurrent.Exchanger;

public class ExchangerTest {
    static Exchanger<String> exchanger = new Exchanger<>();

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String t1 = "T1";
                try {
                    //线程1交换器拿T1去交换
                    t1 = exchanger.exchange(t1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " " + t1);
            }
        }, "t1").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String t1 = "T2";
                try {
                    //线程2交换器拿T2去交换
                    t1 = exchanger.exchange(t1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //交换成功，拿到线程1的交换的值，线程1也会拿到这里交换过去的值
                System.out.println(Thread.currentThread().getName() + " " + t1);
            }
        }, "t2").start();
    }
}
